package cn.tangshh.universal.core.util;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;

/**
 * 国际化工具类
 *
 * @author Tang
 * @version v1.0
 * @since 2024/05/30
 */
@Slf4j
public class MessageUtil {
    private static MessageSource SOURCE = null;
    private static boolean ENABLE = false;

    static {
        try {
            SOURCE = SpringUtil.getBean(MessageSource.class);
            ENABLE = true;
        } catch (Exception e) {
            log.warn("国际化功能未开启");
        }
    }

    private MessageUtil() {
    }

    /**
     * 消息转换
     *
     * @param key  key
     * @param args 参数
     * @return {@link String }
     */
    public static String convert(String key, Object... args) {
        if (ENABLE && RegexUtil.verify(key, "(\\w+.)*\\w+"))
            try {
                return SOURCE.getMessage(key, args, LocaleContextHolder.getLocale());
            } catch (NoSuchMessageException e) {
                if (log.isDebugEnabled()) {
                    log.debug("i18n转换失败：{}", e.getMessage());
                }
            }
        return key;
    }
}